/*
Package serial provides a cross-platform serial reader and writer.
*/
package serial

import (
	"errors"
	"io"
	"openzbox.com/driver/conn/driver/driverreg"
	"time"
)

var (
	// ErrTimeout is occurred when timing out.
	ErrTimeout = errors.New("serial: timeout")
)

// Config is common configuration for serial port.
type Config struct {
	//端口名称
	PortName	string	`json:"portName"`
	// Device path (/dev/ttyS0)
	Address string	`json:"address"`
	// Baud rate (default 19200)
	BaudRate int		`json:"baudRate"`
	// Data bits: 5, 6, 7 or 8 (default 8)
	DataBits int		`json:"dataBits"`
	// Stop bits: 1 or 2 (default 1)
	StopBits int		`json:"stopBits"`
	// Parity: N - None, E - Even, O - Odd (default E)
	// (The use of no parity requires 2 stop bits.)
	Parity string		`json:"parity"`
	// Read (Write) timeout.
	Timeout time.Duration	`json:"timeout"`
	// Configuration related to RS485
	RS485 RS485Config		`json:"rs485,omitempty"`
}

// platform independent RS485 config. Thie structure is ignored unless Enable is true.
type RS485Config struct {
	// Enable RS485 support
	Enabled bool	`json:"enabled"`
	// Delay RTS prior to send
	DelayRtsBeforeSend time.Duration	`json:"delayRtsBeforeSend"`
	// Delay RTS after send
	DelayRtsAfterSend time.Duration			`json:"delayRtsAfterSend"`
	// Set RTS high during send
	RtsHighDuringSend bool			`json:"rtsHighDuringSend"`
	// Set RTS high after send
	RtsHighAfterSend bool			`json:"rtsHighAfterSend"`
	// Rx during Tx
	RxDuringTx bool			`json:"rxDuringTx"`
}

// Port is the interface for controlling serial port.
type Port interface {
	io.ReadWriteCloser
	// Connect connects to the serial port.
	Open(*Config) error
}

// Open opens a serial port.
func Open(c *Config) (p Port, err error) {
	p = New()
	err = p.Open(c)
	return
}

// Open creates an io.ReadWriteCloser based on the supplied options struct.
/*func Open(options OpenOptions) (io.ReadWriteCloser, error) {
	// Redirect to the OS-specific function.
	return openInternal(options)
}
*/
// Rounds a float to the nearest integer.
/*func round(f float64) float64 {
	return math.Floor(f + 0.5)
}*/

// driverSerial implements periph.Driver.
type driverSerial struct {
}

func (d *driverSerial) String() string {
	return "serialx"
}

func (d *driverSerial) Prerequisites() []string {
	return nil
}

func (d *driverSerial) After() []string {
	return nil
}

func (d *driverSerial) Init() (bool, error) {
	return true, nil
}

func init() {
	driverreg.MustRegister(&drv)
}

var drv driverSerial